﻿package at.geoathome.ui.buttons
{
	import com.kronomy.ui.UIUtils;
	import com.kronomy.ui.buttons.*;
	
	/**
	* ...
	* @author Georg Kamptner
	*/
	public class RadioButtonSets
	{
		private var _sets:Object;
		private static var _instance:RadioButtonSets
		
		
		public function RadioButtonSets(singleton_enforcer:SingletonEnforcer)
		{
			_sets = new Object();
		}
		
		public  static function getInstance():RadioButtonSets
		{
		  if (_instance == null)
			_instance = new RadioButtonSets(new SingletonEnforcer());
			
		  return _instance;
		}
		
		public function addRadioButton(btn:RadioButton, set_id:String):void
		{	
			if (!setExists(set_id))
				addSet(set_id);
			
			_sets[set_id].push(btn);
		}
		
		public function removeRadioButton(btn:RadioButton, set_id:String):void // not tested
		{
			if (!setExists(set_id))
				return;
			
			var index:int = getButtonIndex(btn, set_id);
			if (index < 0) return; // stop if button is not part of the set
			
			_sets[set_id][index] = null; // remove button from set
		}
		
		public function handleButtonCheck(btn:RadioButton, set_id:String):void
		{	
			if (btn == null) return;
			if (!setExists(set_id)) return;
			
			var str:String = "";
			var i:uint = 0;
			var l:uint = _sets[set_id].length;
			for (; i<l; ++i)
			{
				if (_sets[set_id][i] == null)
					continue;

				if (_sets[set_id][i] != btn && btn.checked)  // uncheck all other buttons of this set
				{
					_sets[set_id][i].checked = false;
				}
			}
		}
		
		private function addSet(set_id:String):void
		{
			_sets[set_id] = new Array();
		}
		
		private function setExists(set_id:String):Boolean
		{
			return (_sets[set_id] != undefined && _sets[set_id] != null);
		}
		
		private function getButtonIndex(btn:RadioButton, set_id:String):int // no t tested
		{
			if (btn == null) return -1;
			if (!setExists(set_id)) return -1;
			
			var i:uint = 0;
			var l:uint = _sets[set_id].length;
			for (; i < l;++i)
			{
				if (_sets[set_id][i] == null)
					continue;
				if (_sets[set_id][i] == btn)
					return i;
			}
			
			return -1;
		}
	}
	
}

class SingletonEnforcer {}